#include "quicksort.h"
#include "../stream/inputbufferstream.h"
#include "../stream/outputbufferstream.h"
#include <sstream>
using namespace std;

void split_data(char* fileName, int totalNum, int numOfSplits)
{
	inputbufferstream is;
	outputbufferstream os[numOfSplits];
	is.open_s(fileName);
	vector<int> numbers;
	for(int j=0;j<numOfSplits;j++)
	{
		numbers.clear();
		for (int i =0;i<totalNum/numOfSplits; i++)
		{
			numbers.push_back(is.read_next());
		}
		quicksort(numbers, 0 ,numbers.size());
		stringstream ss;
		ss << j;
		os[j].create(ss.str().c_str());
		for (int i = totalNum/numOfSplits;i>0; i--)
		{
			os[j].write_s(numbers[i]);
		}
		os[j].close_s();
	}

}

void quicksort(vector<int> &w, int n, int m)
{
	if(m<=n)
		return;
	int i = n, j = m - 1, pivot = w[m], temp = 0;
	while (i <= j)
	{
	 	while (w[j] >= pivot)
	        {
	        	j--;
		        if (j <= n)
		        	break;
	        }
		while (w[i] <= pivot)
	        {
			i++;
		        if (i >= m)
		        	break;
	        }
		if (i < j)
	        {
	                temp = w [j];
	                w [j] = w [i];
                        w [i] = temp;
		}

	}
	temp = w[i];
	w[i] = w[m];
	w[m] = temp;

	quicksort (w, n, i - 1);
	quicksort (w, i + 1, m);
}

